package main

import (
	"flag"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/inner/uuid"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"
	"net"
	"os"
	"os/signal"
	"service_base_shop/jwt_srv/global"
	"service_base_shop/jwt_srv/handler"
	"service_base_shop/jwt_srv/initialize"
	"service_base_shop/jwt_srv/proto"
	"service_base_shop/user_srv/utils/register/consul"
	"syscall"
)
func GetFreePort() (int, error) {
	addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
	if err != nil {
		return 0, err
	}

	l, err := net.ListenTCP("tcp", addr)
	if err != nil {
		return 0, err
	}
	defer l.Close()
	return l.Addr().(*net.TCPAddr).Port,  nil
}

func main()  {
	IP := flag.String("ip", "0.0.0.0", "ip地址")
	Port := flag.Int("port", 0, "端口号")
	flag.Parse()
	if *Port == 0{
		*Port, _ = GetFreePort()
	}
	//设置日志
	initialize.InitLogger()

	//设置配置文件
	initialize.InitConfig()

	initialize.InitDB()
	//初始化grpc 服务
	server := grpc.NewServer()

	//注册
	protopb.RegisterJwtServer(server,&handler.Jwt{})

	//心跳检测
	grpc_health_v1.RegisterHealthServer(server,health.NewServer())
	service_id,_ := uuid.NewV4()
	serviceId := fmt.Sprintf("%s", service_id)
	register_client :=  consul.NewRegistryClient(global.ServerConfig.ConsulInfo.Host,global.ServerConfig.ConsulInfo.Port)

	if err := register_client.Register(global.ServerConfig.Host,*Port,global.ServerConfig.Name,[]string{"jwt","jwt_srv"},serviceId); err != nil{
		zap.S().Panic("服务注册失败:", err.Error())
	}

	fmt.Println(*IP,*Port,service_id)

	go func() {
		//监听
		lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", *IP, *Port))
		if err != nil {
			zap.S().Panic("监听:", err.Error())
		}
		//启动
		if  err := server.Serve(lis); err != nil{
			zap.S().Panic("启动失败:", err.Error())
		}
	}()
	//注销服务
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	if err := register_client.DeRegister(serviceId); err != nil {
		zap.S().Info("注销失败:", err.Error())
	}else{
		zap.S().Info("注销成功:")
	}
}
